package com.king.base;

import java.io.IOException;

import com.google.common.base.Throwables;

/**
 * @author taomk
 * @version 1.0
 * @since 15-1-31 下午5:28
 */
public class ThrowablesTest {

	public static void main(String[] args) throws Exception {
		testThrowables();
	}

	public static void testThrowables() throws Exception {
		try {
			throw new Exception();
		} catch (Throwable t) {
			// Guava的异常链处理方法：
			// 1.Throwable getRootCause(Throwable)
			// 2.List<Throwable> getCausalChain(Throwable)
			// 3.String getStackTraceAsString(Throwable)
			String ss = Throwables.getStackTraceAsString(t);
			System.out.println("ss:" + ss);
			// 1.RuntimeException propagate(Throwable)：把throwable包装成RuntimeException，用该方法保证异常传递，抛出一个RuntimeException异常
			Throwables.propagate(t);
		}

		try {
			throw new IOException();
		} catch (Throwable t) {
			// 2.void propagateIfInstanceOf(Throwable, Class<X extends Exception>) throws X：当且仅当它是一个X的实例时，传递throwable
			Throwables.propagateIfInstanceOf(t, IOException.class);

			// 3.void propagateIfPossible(Throwable)：当且仅当它是一个RuntimeException和Error时，传递throwable.
			// 4.void propagateIfPossible(Throwable, Class<X extends Throwable>) throws X：当且仅当它是一个RuntimeException和Error时，或者是一个X的实例时，传递throwable。
			Throwables.propagateIfPossible(t, IOException.class);
			throw Throwables.propagate(t);
		}
	}
}
